<template>
  <div>
    <section style="margin-bottom: 5px">
      <Form :model="so" :label-width="90">
        <Row>
          <form-field label="弹性云主机" span="6">
            <Select id="ecsId" v-model="so.ecsId" @on-change="OnSearchMetrics">
              <OptionGroup v-for="(group, index) of groupedServers" :label="group.describle" :key="'ecs:' + index">
                <Option v-for="(item, cIndex) in group.items" :value="item.id" :label="item.name" :key="'ecs:' + index + '/' + cIndex" />
              </OptionGroup>
            </Select>
          </form-field>
          <form-field label="监控粒度" span="3" type="select" v-model="so.period" :datas="periods" />
          <form-field label="聚合方式" span="3" type="select" v-model="so.filter" :datas="filters" />
          <form-field label="时间区间" span="8">
            <DatePicker type="datetimerange" v-model="dateRanges" split-panels format="yyyy-MM-dd HH:mm" />
          </form-field>
          <form-field span="2" :label-width="10">
            <Button type="primary" icon="md-search" shape="circle" @click="OnSearchMetrics">查询</Button>
          </form-field>
        </Row>
      </Form>
    </section>
    <div class="bg-success" style="margin-bottom: 5px">
      <span>
        <b>数据更新时间：</b>
        {{ executeDate }}
      </span>
      <span style="margin-left: 50px" class="text-danger">
        <b>距下一次更新剩余：</b>
        {{ cutdownSeconds }}秒
      </span>
    </div>
    <section>
      <div id="canvas" style="width: 100%; height: 580px"></div>
    </section>
  </div>
</template>

<script>
  import * as echarts from 'echarts';

  let intevalHandler;

  export default {
    data() {
      return {
        groupedServers: [],
        metrics: [],
        echarts: null,
        echartsOption: null,
        executeDate: '',
        cutdownSeconds: 60,
        periods: [
          {
            text: '实时',
            value: 1
          },
          {
            text: '5分钟',
            value: 300
          },
          {
            text: '20分钟',
            value: 1200
          },
          {
            text: '1小时',
            value: 3600
          },
          {
            text: '4小时',
            value: 14400
          },
          {
            text: '1天',
            value: '86400'
          }
        ],
        filters: [
          {
            text: '最大',
            value: 'max'
          },
          {
            text: '最小',
            value: 'min'
          },
          {
            text: '平均',
            value: 'average'
          },
          {
            text: '求和',
            value: 'sum'
          },
          {
            text: '方差',
            value: 'variance'
          }
        ],
        so: {
          ecsId: '',
          period: 300,
          filter: 'average',
          from: '',
          to: ''
        },
        dateRanges: []
      };
    },
    methods: {
      RenderMetric() {
        let that = this;

        this.so.from = this.dateRanges[0];
        this.so.to = this.dateRanges[1];

        if (this.so.from == '' || this.so.to == '') {
          this.$Notice.warning({
            title: '警告！',
            desc: '开始时间或截止时间不能为空！'
          });

          return;
        }

        if (Date.parse(this.so.from) >= Date.parse(this.so.to)) {
          this.$Notice.warning({
            title: '警告！',
            desc: '开始时间不能超过截止时间！'
          });

          return;
        }

        let metricPromise = metric =>
          new Promise((resolve, reject) => {
            let data = Object.assign(
              {
                metricName: metric.name
              },
              this.so
            );

            this.echartsOption.legend.data.push(metric.text);

            this.$http.post(`/api/hwcloud/ecs/info/${this.so.ecsId}`, data).then(res => {
              res.MetricText = metric.text;
              res.MetricUnit = metric.unit;

              resolve(res);
            });
          });

        let now = new Date();

        this.executeDate = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;

        var ps = this.metrics.map(item => metricPromise(item));

        this.echartsOption.series.length = 0;

        Promise.all(ps).then(values => {
          values.forEach(rs => {
            that.echartsOption.xAxis.data = rs.datapoints.map(function (m) {
              var date = new Date(m.timestamp);

              return date.format('yyyy-MM-dd HH:mm');
            });

            that.echartsOption.series.push({
              name: rs.MetricText,
              type: 'line',
              yAxisIndex: rs.MetricUnit == '%' ? 0 : 1,
              data: rs.datapoints.map(function (m) {
                return m[that.so.filter];
              })
            });
          });

          // 使用刚指定的配置项和数据显示图表。
          that.echarts.setOption(that.echartsOption);
        });

        if (intevalHandler) {
          clearInterval(intevalHandler);

          intevalHandler = null;
          that.cutdownSeconds = 60;
        }

        intevalHandler = setInterval(() => {
          that.cutdownSeconds--;

          if (that.cutdownSeconds <= 0) {
            this.OnSearchMetrics();
          }
        }, 1000);
      },
      OnSearchMetrics() {
        this.echartsOption.xAxis.data.length = 0;
        this.echartsOption.series.length = 0;

        // this.RenderMetric();
      },
      ResizeChartPanel(area) {
        document.getElementById('canvas').style.height = area.height - 125 + 'px';
      }
    },
    mounted() {
      this.$bus.on('windowResizeChanged', client => {
        this.ResizeChartPanel(client);

        this.echarts.resize();
      });

      let now = new Date();
      let next = new Date();

      next.setDate(now.getDate() + 1);

      this.dateRanges[0] = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} 00:00:00`;
      this.dateRanges[1] = `${next.getFullYear()}-${next.getMonth() + 1}-${next.getDate()} 00:00:00`;

      this.$http.get('/api/hwcloud/servers').then(res => {
        this.metrics = res.metrics;
        this.so.ecsId = res.servers[0].id;

        let groups = [];

        res.servers.forEach(c => {
          let group = groups.find(g => g.projectId == c.projectId);

          if (group) {
            group.items.push(c);
          } else {
            groups.push({
              projectId: c.projectId,
              describle: c.describle,
              items: [c]
            });
          }
        });

        this.groupedServers = groups;

        // 图表呈现
        // this.RenderMetric();
      });

      this.$nextTick(() => {
        let area = this.getClientArea();

        this.ResizeChartPanel(area);

        this.echarts = echarts.init(document.getElementById('canvas'));

        this.echartsOption = {
          grid: {
            top: '80px'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              animation: false
            }
          },
          legend: {
            data: []
          },
          xAxis: {
            type: 'category',
            axisLabel: {
              formatter: '{value}'
            },
            data: []
          },
          yAxis: [
            {
              type: 'value',
              name: '百分比',
              min: 0,
              max: 100,
              position: 'left',
              axisLabel: {
                formatter: '{value}%'
              }
            },
            {
              type: 'value',
              name: '流量',
              position: 'right',
              axisLabel: {
                formatter: '{value}字节/秒'
              }
            }
          ],
          series: []
        };

        // 使用刚指定的配置项和数据显示图表。
        this.echarts.setOption(this.echartsOption);
      });
    },
    activated() {
      const that = this;

      this.$nextTick(() => {
        intevalHandler = setInterval(() => {
          that.cutdownSeconds--;

          if (that.cutdownSeconds <= 0) {
            this.OnSearchMetrics();
          }
        }, 1000);
      });
    },
    deactivated() {
      // 销毁定时器
      if (intevalHandler) {
        clearInterval(intevalHandler);
      }
    }
  };
</script>

<style lang="less">
  .ivu-date-picker {
    width: 100%;
  }
</style>
